from django.shortcuts import render

from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from . import global_data
import json

# Create your views here.


def index(request):
  return JsonResponse({"a": "1", "b": "2"})


@csrf_exempt
def get_data(request):
  if request.method == "GET":
    return JsonResponse({"request get": request.GET['a']})

  if request.method == "POST":
    return JsonResponse({"request post": request.POST['a']})


def home(request):
  return render(request, 'index.html')


@csrf_exempt
def add_data(request):
  if request.method == "POST":
    account_name = request.POST["account_name"] if "account_name" in request.POST else "a"
    channel_name = request.POST["channel_name"] if "channel_name" in request.POST else "a"
    print(request.POST["data"])
    global_data.add_data(account_name, channel_name, json.loads(request.POST["data"]))
  return HttpResponse("success")


def clear_data(request):
  if request.method == "POST":
    if "channel_name" not in request.POST or request.POST["channel_name"] == "":
      global_data.clear_account_data(request.POST["account_name"])
    else:
      global_data.clear_data(request.POST["account_name"], request.POST["channel_name"])
  return HttpResponse("success")


@csrf_exempt
def data_chart(request):
  account_name = request.POST["account_name"] if "account_name" in request.POST else "a"
  channel_name = request.POST["channel_name"] if "channel_name" in request.POST else "a"

  jr = JsonResponse(data=global_data.get_data(account_name, channel_name))
  return jr


def get_data_struct(request):
  if request.method == "GET":
    return JsonResponse(global_data.get_data_struct())
  return HttpResponse("failed")
